package com.qg.auth.handler.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;

import com.qg.auth.handler.WebContextHandler;
import com.qg.auth.util.JwtUtil;
import com.qg.base.constants.WebConstant;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @Author QG
 * @Date 2023/5/25 14:36
 * @description jwt实现
 **/
@Component("webContextHandler")
@ConditionalOnProperty(name = "system.login.method", havingValue = "jwt", matchIfMissing = false)
public class WebContextJwt implements WebContextHandler {

    private static final Logger logger = LoggerFactory.getLogger(WebContextJwt.class);

    @Override
    public <T> T getUser(Class<T> clazz) throws Exception {
        HttpServletRequest request = getRequest();
        String jwt = request.getHeader(WebConstant.TOKEN);
        String subject = JwtUtil.parseJWT(jwt).getSubject();
        T t = JSONObject.parseObject(subject, clazz);
        return t;
    }

    /**
     * 将用户信息以Map形式返回
     *
     * @return
     * @throws Exception
     */
    @Override
    public Map getUser() throws Exception {
        String token = getTokenString(getRequest());
        if(token == null) {
            return null;
        }
        Claims claims = JwtUtil.parseJWT(token);
        if(claims == null) {
            return null;
        }
        String subject = claims.getSubject();
        return JSONObject.parseObject(subject, Map.class);
    }

    @Override
    public String getTokenString(HttpServletRequest request) {
        if(request == null) {
            request = getRequest();
        }
        String token = request.getHeader(WebConstant.TOKEN);
        if(StrUtil.isBlank(token)) {
            return null;
        }
        return token;
    }

    @Override
    public String setUser(Object user) {
        if(user == null) {
            logger.debug("user params is null or empty");
        }
        String jwt = JwtUtil.createJWT(JSONObject.toJSONString(user));
        getResponse().setHeader(WebConstant.TOKEN,jwt);
        return jwt;
    }

    @Override
    public void setUser(String token) {
        logger.debug("当前为空实现");
    }

    @Override
    public void removeUser() {

    }
}
